
# # -*- coding:utf-8 -*-
# from flask import Flask
# from flask_sqlalchemy import SQLAlchemy  # 操作数据库的扩展包
# from flask_script import Manager  # 用命令操作的扩展包
# from flask_migrate import Migrate,MigrateCommand  # 操作数据库迁移文件的扩展包
# import pymysql
# from flask_cors import CORS
# app = Flask(__name__)
# CORS(app,supports_credentials=True)
# app.debug = True
# app.config["SQLALCHEMY_DATABASE_URI"] = "mysql+pymysql://root:123@localhost/second_flask"
# app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False

# db = SQLAlchemy(app)
# manager = Manager(app)
# # 创建迁移对象
# migrate = Migrate(app,db)
# # 将迁移文件的命令添加到‘db’中
# manager.add_command('db',MigrateCommand)


# class Role(db.Model):
#     __tablename__ = "table_roles"
#     id = db.Column(db.Integer,primary_key=True)
#     name = db.Column(db.String(16),unique=True)
#     info = db.Column(db.String(100))
#     Users = db.relationship("User",backref='role')


# class User(db.Model):
#     __tablename__ = "table_users"
#     id = db.Column(db.Integer,primary_key=True)
#     name = db.Column(db.String(16),unique=True)
#     info = db.Column(db.String(200))

#     role_id = db.Column(db.Integer,db.ForeignKey("table_roles.id"))



# @app.route('/login',methods=['POST'])
# def login():
#     data = json.loads(request.form.get('data'))
#     username = data['username']
#     password = data['password']
#     print (username)
#     print (password)
#     aaa = User.query.get(1)
#     # print(aaa.id,aaa.name)
#     print(aaa.id)
#     return "46575"


# @app.route('/')
# def hello_world():

#     #增加一条信息到Role数据表中
    
#     # 方式1:
#     # aaa = Role()
#     # aaa.name = 'asfdsdaf'
#     # aaa.info = 'fasdfa'
#     # db.session.add(aaa)

#     #方式2：
#     # db.session.add(Role(name='asdfg',info='aaaaa'))
#     # db.session.commit()


#     #增加多条信息到Role数据表中
#     # db.session.add_all([Role(name='name_2',info='aaaaa'),Role(name='name_1',info='aaa')])
#     # db.session.commit()

#     # 获取所有数据
#     users=Role.query.all()
#     for user in users:
#         print(user.name)


#     # 获取第一条数据
#     user1=Role.query.first()
#     print(user1.name)

#     # 获取name=zhangsan的user
#     user2=Role.query.filter_by(name='name_2').first()
#     print(user2.name)


#     #更新数据
#     # user3 = Role.query.filter_by(name='zhangsan', id=1).first()
#     # user3.name='zhangsi'
#     # db.session.commit()


#     #删除
#     # user3 = Role.query.filter_by(name='zhangsi', id=1).first()
#     # db.session.delete(user3)
#     # db.session.commit()

#     return 'Hello World!'


# if __name__ == '__main__':

#     manager.run()
    






from flask import Flask,template_rendered,request,session
import json
from flask_cors import CORS
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate,MigrateCommand
from flask_script import Manager
import functools
from flask import make_response

app = Flask(__name__)
CORS(app,supports_credentials=True)

app.debug = True
app.config["SQLALCHEMY_DATABASE_URI"] = "mysql+pymysql://root:123@localhost/flask_one"
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False

# db = SQLAlchemy(app)
# manager = Manager(app)
# # 创建迁移对象
# migrate = Migrate(app,db)
# # 将迁移文件的命令添加到‘db’中
# manager.add_command('db',MigrateCommand)


db = SQLAlchemy(app)
manager = Manager(app)

# 创建迁移对象
migrate = Migrate(app,db)

# 将迁移文件的命令添加到'db'中
manager.add_command('db',MigrateCommand)


class user(db.Model):
    __tablename__ = 'user'
    id = db.Column(db.Integer,primary_key=True)
    name = db.Column(db.String(16),unique=True)


class User(db.Model):
    __tablename__ = 'table_User'
    id = db.Column(db.Integer,primary_key = True)
    name = db.Column(db.String(16),unique=True)
    password = db.Column(db.String(16))
    phone = db.Column(db.String(16))
    mail = db.Column(db.String(50))
    sex = db.Column(db.String(5))
    # grade = db.Column(db.Enum('vip','standard'),server_default='standard',nullable=False)



# db.session.add(user(name='aaaassss'))
# db.session.commit()


class user_power(db.Model):
    __tablename__ = 'user_power'
    id = db.Column(db.Integer,primary_key = True)
    name = db.Column(db.String(10),unique=True)
    power_grade = db.Column(db.Enum('Leader','Member','Ordinary'),server_default='Ordinary',nullable=False)



class roles(db.Model):
    __tablename__ = 'roles'
    id = db.Column(db.Integer,primary_key=True)
    user_roles = db.Column(db.String(10),unique=True)


class permission(db.Model):
    __tablename__ = 'permission'
    id = db.Column(db.Integer,primary_key=True)
    user_permission = db.Column(db.Enum('Leader','Member','Ordinary'),server_default='Ordinary',nullable=False)

class roles_user(db.Model):
    __tablename__ = 'roles_user'
    id = db.Column(db.Integer,primary_key=True)
    user_id = db.Column(db.Integer,db.ForeignKey('table_User.id'))
    roles_id = db.Column(db.Integer,db.ForeignKey('roles.id'))


class roles_permission(db.Model):
    __tablename__ = 'roles_permission'
    id = db.Column(db.Integer,primary_key=True)
    rolues_id = db.Column(db.Integer,db.ForeignKey('roles.id'))
    permission_id = db.Column(db.Integer,db.ForeignKey("permission.id"))


def quanxian(func):
    @functools.wraps(func)
    def aaa():
        s = 1

        if s ==1:
            print('该用户存在执行权限')
            return func()
        else:
            print('该用户没有执行权限')
            msg = json.dumps({'type':'flase'})
            return msg
    return aaa



@app.route('/login',methods=['POST'])
@quanxian
def login():
    data = json.loads(request.form.get('data'))
    # print(data['username'])
    # data = request.get('data')
    
    user2=User.query.filter_by(name=data['username']).first()
    
    try:
        if user2.name:
            if user2.name == data['username'] and user2.password == data['password']:
                # print(user2.password,data['password'])
                # res=make_response('Hello World')
                # res.set_cookie('Name','Hyman',max_age=60*60*24)

                print('message is ok')
                msg = json.dumps({'type':'1'})
                return msg
            else:
                a = json.dumps({'type':'0'})
                return a
        # else:
        #     a = json.dumps({'type':'0'})
        #     return a
    except:
        a = json.dumps({'type':'0'})
        return a

    

@app.route('/register',methods=['POST'])
def register():
    data = json.loads(request.form.get('data'))
    print(data)

    try:

        user_save = User()
        user_save.name = data['username']
        user_save.password = data['password']
        user_save.phone = data['phone']
        user_save.mail = data['mail']
        user_save.sex = data['sex']
        db.session.add(user_save)

        user_id = User.query.filter_by(name = data['username']).first().id
        user_role = roles_user()
        user_role.user_id = user_id
        user_role.roles_id = 1
        db.session.add(user_role)

        db.session.commit()

    except:
        return json.dumps({'state':'0'})

    return json.dumps({'state':'1'})



@app.route('/',methods=['GET'])
def index():
    # print(request.cookies.get('Name'),'================')
    roles_ = roles_user.query.filter_by(user_id = 34).first().roles_id
    print(roles_,type(roles_),'+++++++++++++++')
    return 'hello everyday'


#执行超级用户的命令，增删改查
@app.route('/admin/command',methods=['POST'])
def command():
    # data = json.loads(request.form.get('data'))
    print('请求成功')
    a = json.dumps({'a':1})
    return a


@app.route('/admin/index',methods=['POST'])
def admin_index():

    msg = User.query.all()
    l = []
    l1 = []
    for i in msg:
        l1.append(i.name)
        l1.append(i.password)
        l1.append(i.phone)
        l1.append(i.mail)
        l1.append(i.sex)
        l.append(l1)
        l1 = []
        # l.append(i.name)
    # print(l)

    data = {'user':l}
    # data = {'user':msg}
    # print(msg,type(msg),'++++++++++++++++++')

    return json.dumps(data)

@app.route('/admin/login',methods=['POST'])
def admin():

    data = json.loads(request.form.get('data'))
    print(data)
    msg = User.query.all()
    name = []
    pws = []
    for i in msg:
        name.append(i.name)
        pws.append(i.password)
    print(name,pws)
    try:
        user=User.query.filter_by(name=data['username']).first()
        roles_ = roles_user.query.filter_by(user_id = user.id).first().roles_id
        print(user)
        # if data['username'] in name and data['password'] in pws:
        if data['username'] == user.name and data['password'] == user.password and roles_ > 1:
            res_data = json.dumps({'用户权限':"OK"})
            session.name = data['username']
            session.pwd = data['password']
            print(session.name,session.pwd,'-------------------')

            return res_data
        else:
            res_data = json.dumps({"用户权限":"用户名与密码不匹配"})
            return res_data
    except:
        res_data = json.dumps({'用户权限':"用户名或密码错误"})
        return res_data


if __name__ == '__main__':
    manager.run()